package com.dmwork.service.customer.service.impl;

import com.dmwork.common.base.result.ExceptionUtils;
import com.dmwork.service.customer.properties.SmsProperties;
import com.dmwork.service.customer.service.SmsService;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.sms.v20190711.SmsClient;
import com.tencentcloudapi.sms.v20190711.models.SendSmsRequest;
import com.tencentcloudapi.sms.v20190711.models.SendSmsResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class SmsServiceImpl implements SmsService {

    @Autowired
    private SmsProperties smsProperties;
    @Autowired
    private SmsClient smsClient;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean sendSms(String phoneNumber) {
        try {
            SendSmsRequest request = new SendSmsRequest();
            request.setSmsSdkAppid(smsProperties.getAppid());
            request.setSign(smsProperties.getSign());
            request.setTemplateID(smsProperties.getTemplateID());
            //设置发送的目标手机号
            String[] phoneNumbers = {"+86" + phoneNumber};
            request.setPhoneNumberSet(phoneNumbers);
            //设置模板参数，即验证码
            String code = new Random().nextInt(100000)+"";
            String[] verificationCode = {code};
            request.setTemplateParamSet(verificationCode);

            SendSmsResponse response = smsClient.SendSms(request);
            if (response.getSendStatusSet()[0].getCode().equals("Ok")) {
                redisTemplate.opsForValue().set(phoneNumber, code, 10, TimeUnit.MINUTES);
                return true;
            }else {
                return false;
            }
        } catch (TencentCloudSDKException e) {
            ExceptionUtils.getMessage(e);
            return false;
        }
    }
}
